package com.example.blog.utils;

import com.example.blog.constant.Constant;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private static final long JWT_EXPIRATION = 60 * 60 * 1000 * 24;
    private static final String secretStr = "S1pVw08MZAHUTIxYaLQk58K0Ln+Pxty+xZetALA36pw=";
    //解码
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr));



    public static String genJwtToken(Map<String,Object> claim) {

        String token =  Jwts.builder().setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
                .signWith(key)
                .compact();
        System.out.println(token);
        return token;
    }


    public static Claims parseToken(String token) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            body = build.parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error("解析失败，token: {}" ,token);
            return null;
        }
        return body;
    }


    public static Integer getIdByToken(String token) {
        Claims claims = parseToken(token);
        if (claims != null) {
            Integer userId =  (Integer) claims.get(Constant.TOKEN_ID);
            if (userId > 0) {
                return userId;
            }
        }
        return null;
    }
}
